package com.huike.zxing;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import androidx.appcompat.app.AppCompatActivity;

/**
 * 二维码生成demo
 *
 * 代码没什么好说的 就背下来把
 */
public class MainActivity extends AppCompatActivity {

    private ImageView iv_print;
    private  int num;
    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv_print = (ImageView) findViewById(R.id.iv_print);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                num = (int) (Math.random() * 100);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            getCreateRQcodeImage(iv_print,num + "",300,300);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        Toast.makeText(MainActivity.this, num + "", Toast.LENGTH_SHORT).show();

                    }
                });

            }
        },0,5000);
    }

    public  void getCreateRQcodeImage(ImageView imageView ,String content,int weith,int height) throws Exception {
        int w = weith;
        int h = height;

        HashMap<EncodeHintType, String> map = new HashMap<>();
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");
        BitMatrix encode = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, w, h, map);
        int[] pixles = new int[w * h];
        for (int i = 0; i < h ; i++) {
            for (int j = 0; j < w ; j++) {
                if(encode.get(i,j)){
                    pixles[i * w +j] = 0xff000000;
                }else{
                    pixles[i * w +j] = 0xffffffff;

                }
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixles,0,w,0,0,w,h);
        imageView.setImageBitmap(bitmap);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        timer = null;
    }
}
